/**
 * 数据脱敏：敏感数据进行加密处理
 * @param str 要脱敏的数据字符串
 * @param prefixKeep 前缀保留多少位显示
 * @param suffixKeep 后缀保留多少位显示
 * @param preserveChars 替换字符中指定字符不被替换
 * @param replacer 需要替换的字符替换成什么字符
 * @returns 返回脱敏的数据
 */
export const desensitize = (str: string, prefixKeep = 3, suffixKeep = 4, preserveChars: string[] = [], replacer = '*') => {
  const regex = new RegExp(`(?<=.{${prefixKeep}}).{${str.length - prefixKeep - suffixKeep}}(?=.{${suffixKeep}}$)`)
  const preserveSet = new Set(preserveChars)
  return str.replace(regex, match => {
    return Array.from(match)
      .map((char: string) => {
        return preserveSet.has(char) ? char : replacer
      })
      .join('')
  })
}

/**
 * 姓名脱敏
 * @param str
 * @returns
 */
export const nameDesensitize = (str: string) => {
  return desensitize(str, 1, 0)
}

/**
 * 金钱脱敏
 * @param str
 * @returns
 */
export const moneyDesensitize = (str: string) => {
  return desensitize(str, 0, 0, [',', '.'])
}

/**
 * 密码脱敏
 * @param str
 * @returns
 */
export const passwordDesensitize = (str: string) => {
  return desensitize(str, 0, 0)
}

/**
 * 身份证脱敏
 * @param str
 * @returns
 */
export const idCardDesensitize = (str: string) => {
  return desensitize(str, 1, 2)
}

/**
 * 地址脱敏
 * @param str
 * @returns
 */
export const addressDesensitize = (str: string) => {
  return desensitize(str, 6, 0)
}

/**
 * 邮箱脱敏
 * @param str
 * @returns
 */
export const emailDesensitize = (str: string) => {
  return desensitize(str, 1, str.split('@')[1].length + 1)
}

/**
 * 车牌照脱敏
 * @param str
 * @returns
 */
export const carLicenseDesensitize = (str: string) => {
  return desensitize(str, 3, 1)
}

/**
 * 手机号脱敏
 * @param str
 * @returns
 */
export const phoneDesensitize = (str: string) => {
  return desensitize(str, 3, 4)
}

/**
 * 座机号脱敏
 * @param str
 * @returns
 */
export const landlineDesensitize = (str: string) => {
  return desensitize(str, 4, 2)
}

/**
 * 银行卡号脱敏
 * @param str
 * @returns
 */
export const bankCardDesensitize = (str: string) => {
  return desensitize(str, 4, 4, [' '])
}
